package com.common.sdk.net.download.db;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import com.common.sdk.net.download.request.model.DownloadInfo;

public class CacheDatabase {

    private static final HashMap<String, DownloadInfo> canterMap = new HashMap<String, DownloadInfo>();

    @SuppressWarnings("unchecked")
    public static HashMap<String, DownloadInfo> cloneCanterMap() {// TODO
        return (HashMap<String, DownloadInfo>) CacheDatabase.getCanterMap().clone();
    }

    /**
     * 启动线程队列的时候加载数据库
     * @param downloadWaitQueue
    //     */
    // protected static BlockingQueue<DownloadRequest>
    // initialize(BlockingQueue<DownloadRequest> downloadWaitQueue) {
    // Iterator<Entry<String, DownloadInfo>> it =
    // getCanterMap().entrySet().iterator();
    // while (it.hasNext()) {
    // Entry<String, DownloadInfo> entry = it.next();
    // DownloadInfo downloadInfo = (DownloadInfo) entry.getValue();
    // if
    // (downloadInfo.isStartDownload()||downloadInfo.isStopDownload()||downloadInfo.isWaitDownload())
    // {
    // boolean ishas = false;
    // downloadInfo.waitDownload();
    // DownloadRequest absRequest = new DownloadRequest(downloadInfo);
    // Iterator<DownloadRequest> iterator = downloadWaitQueue.iterator();
    // while(iterator.hasNext()){
    // DownloadRequest entryQueue = iterator.next();
    // if(entryQueue.getDownloadInfo().equals(downloadInfo)){
    // ishas = true;
    // break;
    // }
    // }
    // if(!ishas){
    // downloadWaitQueue.add(absRequest);
    // }
    // }
    // }
    // return downloadWaitQueue;
    // }


    /**
     * 取消所有下载
     * @return
     */
    @Deprecated
    protected static boolean pauseAllDownloading() {
        Iterator<Entry<String, DownloadInfo>> it = getCanterMap().entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, DownloadInfo> entry = it.next();
            DownloadInfo downloadInfo = entry.getValue();
            if (!downloadInfo.isFinishDownload()) {
                // 将缓存数据全部变更为取消下载
                downloadInfo.pauseDownload();
                return true;
            }
        }
        return false;
    }

    /**
     * 不能变为public 否则就会对象逸出，变为非线程安全
     * @return
     */
    protected static HashMap<String, DownloadInfo> getCanterMap() {
        if (canterMap.isEmpty()) {
            DownloadFileDetailedHelper.queryAllFileDetailed(canterMap);
        }
        return canterMap; // TODO 可以考虑clone 在想想
    }
}
